package com.mask.im.business.strategy.impl.sendcode;

import com.mask.im.business.model.dto.EmailDTO;
import com.mask.im.business.service.RedisService;
import com.mask.im.business.common.util.EmailUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.task.TaskExecutor;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;

import static com.mask.im.business.common.constant.RedisConstant.EMAIL_REGISTER;


@Service("emailRegisterSendCodeImpl")
public class EmailRegisterSendCodeImpl extends AbstractSendCode {

	@Autowired
	private RedisService redisService;
	@Autowired
	private TaskExecutor taskExecutor;
	@Autowired
	private EmailUtil emailUtil;
	@Override
	public void sendCode(String email) {
//		//校验邮箱是否正确
//		if (!Validator.isEmail(email)) {
//			throw new BusinessException("邮箱格式错误");
//		}
//		//检测验证码是否过期
//		Boolean aBoolean = redisService.hasKey(EMAIL_REGISTER + email);
//		if (BooleanUtil.isTrue(aBoolean)){
//			throw new BusinessException("验证码仍在有效期内");
//		}
		checkEmailAndCode(email,EMAIL_REGISTER);
		//生成验证码
		String code = getCode();
		//将验证码异步发送
		taskExecutor.execute(()->{
			Map<String, Object> map = new HashMap<>();
			map.put("content", "您的注册验证码为: <span style=\"font-weight:700\">"+code+"</span> ,请注意查收,5分钟内有效。");
			EmailDTO emailDTO = EmailDTO.builder()
					.template("common.html")
					.email(email)
					.code(code)
					.subject("邮箱注册验证码")
					.commentMap(map).build();
			emailUtil.sendHtmlMail(emailDTO);
			//将验证码放入redis
			redisService.set(EMAIL_REGISTER+email,code,5*60);
		});
	}

}
